﻿using System;
using System.Text;

/*
 * You are given a text. Write a program that changes the text in all regions
 * surrounded by the tags <upcase> and </upcase> to uppercase. The tags cannot be nested.
 */

namespace UpCaseTag
{
    class UpCaseTag
    {
        static string ToUpperCase(string text)
        {
            StringBuilder result = new StringBuilder();
            bool brokenTag = false;
            int index = 0;

            while (true)
            {
                int startIndex = text.IndexOf("<upcase>", index);
                if (startIndex == -1)
                {
                    break;
                }

                int endIndex = text.IndexOf("</upcase>", startIndex + 5);

                if (endIndex == - 1)
                {
                    brokenTag = true;
                    break;
                }

                result.Append(text.Substring(index, startIndex - index));
                result.Append(text.Substring(startIndex + 8, endIndex - startIndex - 8).ToUpper());
                index = endIndex + 9;
            }

            if (index < text.Length)
            {
                result.Append(text.Substring(index));
            }

            if (brokenTag || result.Length < 0)
            {
                return text;
            }

            return result.ToString();
        }

        static void Main()
        {
            string text = "We are leaving in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
            Console.WriteLine(ToUpperCase(text));
        }
    }
}
